package org.phalanx.zip;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.Deflater;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipFileArchiveWriter {
	private File zipFileArchive;
	ZipOutputStream zOut;
	
	public ZipFileArchiveWriter(){}
	
	public ZipFileArchiveWriter(File file) throws IOException{
		this.setZipFile(file);
	}
	
	private void setZipFile(File file) throws IOException{
		zipFileArchive = file;
	}
	
	public void setZipFileByName(String fileName) throws IOException {
		zipFileArchive = new File(fileName);
	}
	
	public boolean isFileExist(){
		boolean isExists = false;
		
		if (zipFileArchive != null){
			isExists = zipFileArchive.exists();
		}
		
		return isExists;
	}
	
	public void openArchive() throws IOException{
		zOut = new ZipOutputStream(new FileOutputStream(zipFileArchive));
	}
	
	public boolean writeBinaryDataToArchive(String archiveFileName, byte[] writeableByte){
		boolean isSuccess = false;
		
		ZipEntry z = new ZipEntry(archiveFileName);

		try {
			Deflater d = new Deflater();

			d.setInput(writeableByte);
			d.finish();

			zOut.setLevel(9);
			zOut.putNextEntry(z);
			zOut.write(writeableByte);
			isSuccess = true;
		} catch (IOException ie){}

		return isSuccess;
	}
	
	public boolean writeStringDataToArchive(String archiveFileName, String writeableText){
		return writeBinaryDataToArchive(archiveFileName, writeableText.getBytes());
	}

	public boolean writeDirectory(String dirName){
		boolean isSuccess = false;
		
		if (!dirName.endsWith("/")){
			dirName += "/";
		}
		
		ZipEntry z = new ZipEntry(dirName);
		try {
			zOut.putNextEntry(z);
			isSuccess = true;
		} catch (IOException ie){}
		
		return isSuccess;
	}
	
	public void close() throws IOException{
		zOut.close();
	}
}
